from datetime import datetime

from PyQt6.QtCharts import QPieSeries, QChart, QChartView, QBarSeries, QLineSeries, QBarSet, QBarCategoryAxis, \
    QValueAxis
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QIcon, QPen, QColor, QPainter
from PyQt6.QtPrintSupport import QPrintPreviewDialog

import netshop
from ui.SaleAnalysis_ui import Ui_MainWindow

from PyQt6.QtWidgets import QMainWindow, QGridLayout


class SaleAnalysis(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(SaleAnalysis, self).__init__()
        self.setupUi(self)
        self.setWindowIcon(QIcon('image/netshop.jpg'))
        self.setWindowFlag(Qt.WindowType.MSWindowsFixedSizeDialogHint)
        self.pbPrint.clicked.connect(self.printFigure)

        self.initData()
        self.analyByType()
        self.analyByMonth()

    def initData(self):
        # 加载数据:
        # self.saledata: [[ 订单号 商品号 数量 价格 金额 类别 月份 ] ...]
        # self.typeset: { 类别: 销售额 }
        # self.money_m: [ 各月份销售额 ]
        orders = netshop.sheet('订单表')
        orders = dict(zip([order['订单号'] for order in orders], orders))
        types = netshop.query_dict('商品分类表', 0, 1)
        goods = netshop.sheet('商品表')
        goods = dict(zip([good['商品号'] for good in goods], goods))
        order_stats = netshop.sheet('订单项表')
        self.saledata = [[
            stat['订单号'],
            stat['商品号'],
            stat['订货数量'],
            goods[stat['商品号']]['价格'],
            goods[stat['商品号']]['价格'] * stat['订货数量'],
            types[goods[stat['商品号']]['类别编号']],
            orders[stat['订单号']]['下单时间'][5:7]
        ] for stat in order_stats]
        self.typeset = {}
        self.money_m = [0.00 for _ in range(12)]
        self.month = ['%02d' % i for i in range(1, 13)]
        for data in self.saledata:
            # 类别销售额
            if data[5] not in self.typeset:
                self.typeset[data[5]] = 0
            self.typeset[data[5]] += data[4]
            # 月份销售额
            self.money_m[int(data[6]) - 1] += data[4]

    def analyByType(self):
        series = QPieSeries()
        for (type, price) in self.typeset.items():
            series.append(type, price)
        # 扇区外观
        slice = series.slices()[0]
        slice.setExploded(True)
        slice.setLabelVisible(True)
        slice.setPen(QPen(Qt.GlobalColor.red, 2))
        slice.setBrush(Qt.GlobalColor.red)
        # QChart
        chart = QChart()
        chart.addSeries(series)
        chart.createDefaultAxes()
        # 图表
        chart.setTitle('商品按类别销售数据分析')
        chart.setAnimationOptions(QChart.AnimationOption.SeriesAnimations)
        # 图例
        chart.legend().setVisible(True)
        chart.legend().setAlignment(Qt.AlignmentFlag.AlignBottom)

        chartview = QChartView()
        chartview.setChart(chart)
        self.layout1 = QGridLayout(self.frmType)
        self.layout1.addWidget(chartview)

    def analyByMonth(self):
        # 设置数据
        bseries = QBarSeries()
        lseries = QLineSeries()
        monthset = QBarSet('')
        for i in range(0, 12):
            monthset << self.money_m[i]
            lseries.append(i, self.money_m[i])
        bseries.append(monthset)
        lseries.setColor(QColor(255, 0, 0))
        # QChart
        chart = QChart()
        chart.legend().hide()
        chart.addSeries(bseries)
        chart.addSeries(lseries)
        # 坐标轴
        axis_x = QBarCategoryAxis()
        axis_x.setTitleText('月份')
        axis_x.append(self.month)
        chart.addAxis(axis_x, Qt.AlignmentFlag.AlignBottom)
        lseries.attachAxis(axis_x)
        axis_y = QValueAxis()
        axis_y.setTitleText('金额（元）')
        axis_y.setLabelFormat('%d')
        chart.addAxis(axis_y, Qt.AlignmentFlag.AlignLeft)
        lseries.attachAxis(axis_y)
        # 图表
        chart.setTitle('商品按月份销售数据分析')
        chart.setAnimationOptions(QChart.AnimationOption.SeriesAnimations)
        chart.setTheme(QChart.ChartTheme.ChartThemeLight)
        chartview = QChartView(chart)
        chartview.setRenderHint(QPainter.RenderHint.Antialiasing)

        self.layout2 = QGridLayout(self.frmMonth)
        self.layout2.addWidget(chartview)

    def printFigure(self):
        dlg = QPrintPreviewDialog(self)
        dlg.paintRequested.connect(self.handlePrint)
        dlg.exec()

    def handlePrint(self, printer):
        printer = QPainter(printer)
        if self.tabWidget.currentIndex() == 0:
            screen = self.frmType.grab()
        else:
            screen = self.frmMonth.grab()
        printer.drawPixmap(180, 50, screen)
        printer.drawText(100 + self.frmType.width() - 70, 50 + self.frmType.height() - 30,
                         datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S'))
